const { Service } = require('egg')
const { RSAKey } = require('../utils/RSA')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data

      /* * 0.请求主页获取登录所需参数 */
      const homeUrl = `${ctx.state.baseUrl}/jwglxt/xtgl/login_slogin.html`
      const homeRes = await ctx.curl(homeUrl, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      console.log('homeRes', homeRes)
      console.log('homeRes.data', homeRes.data)
      const temCookie = homeRes.headers['set-cookie'] ? homeRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      const insertCookie = temCookie.split(';')[1]
      const csrftoken = /name="csrftoken" value="(.*?)"/.exec(homeRes.data.toString())[1] // 使用正则表达式在源码中提取所需参数
      // console.log('temCookie', temCookie);
      // console.log('csrftoken', csrftoken);
      /* end */

      /* * 1.请求加密参数 */
      const PublicKeyUrl = `${ctx.state.baseUrl}/jwglxt/xtgl/login_getPublicKey.html`
      const PublicKeyRes = await ctx.curl(PublicKeyUrl, {
        method: 'GET',
        headers: {
          Cookie: temCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const { modulus, exponent } = JSON.parse(PublicKeyRes.data.toString()) // 解析出加密所需参数
      // console.log('modulus', modulus);
      // console.log('exponent', exponent);
      /* end */

      /* * 1.构造加密参数 */
      const rsaKey = new RSAKey()
      rsaKey.setPublic(Buffer.from(modulus, 'base64').toString('hex'), Buffer.from(exponent, 'base64').toString('hex'))
      const mm = Buffer.from(rsaKey.encrypt(pwd), 'hex').toString('base64')
      // console.log('mm', mm);
      /* end */

      /* * 2.发送登录请求 */
      const loginUrl = `${ctx.state.baseUrl}/jwglxt/xtgl/login_slogin.html`
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        headers: {
          Cookie: temCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        data: {
          csrftoken,
          language: 'zh_CN',
          yhm: sid,
          mm,
        },
      })
      const setCookie = loginRes.headers['set-cookie'] ? `${loginRes.headers['set-cookie'].map((e) => e.split(';')[0])[1]};${insertCookie}` : ''
      // console.log('loginRes', loginRes);
      // console.log('setCookie', setCookie);
      // console.log('loginRes.status', loginRes.status);
      /* end */

      return { setCookie, status: loginRes.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
